#include "sales_data.h"
#include <iostream>

Sales_data::Sales_data(const std::string &book, const unsigned num,
                       const double sellp, const double salep)
{
    bookNo = book;
    units_sold = num;
    selling_price = sellp;
    sale_price = salep;
    if (selling_price != 0) {
        discount = sale_price / selling_price;  // 计算实际折扣
    }
}

Sales_data::Sales_data(std::istream &is)
{
    read(is, *this);
}

// 用于把两个 ISBN号相同的销售记录合并在一起
Sales_data& Sales_data::combine(const Sales_data &rhs)
{
    units_sold += rhs.units_sold;  // 累加书籍的销售量
    sale_price = (rhs.selling_price * rhs.units_sold + selling_price * units_sold)
            / (rhs.units_sold + units_sold);  // 重新计算实际销售价格
    if (selling_price != 0) {
        discount = sale_price / selling_price;  // 重新计算实际折扣
    }
    return *this;  // 返回合并后的结果
}

Sales_data add(const Sales_data &lhs, const Sales_data &rhs)
{
    Sales_data sum;
    sum.combine(rhs);
    return sum;
}

std::istream& read(std::istream &is, Sales_data &item)
{
    is >> item.bookNo >> item.units_sold >> item.selling_price >> item.sale_price;
    return is;
}

std::ostream& print(std::ostream &os, const Sales_data &item)
{
    os << item.isbn() << " " << item.units_sold << " " << item.selling_price
       << " " << item.sale_price << " " << item.discount;
    return os;
}
